package com.ccx.demo.service.Impl;

import com.ccx.demo.dao.SysUserDao;
import com.ccx.demo.pojo.SysRole;
import com.ccx.demo.pojo.SysUser;
import com.ccx.demo.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
@Component
public class MyDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private SysUserService sysUserService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser userInfo = sysUserService.SelectUsernameByName(username);
        if (userInfo==null){
            System.out.println(userInfo.getId());
            System.out.println(userInfo.getUsername());
            System.out.println(userInfo.getPassword());
            System.out.println(userInfo.getAuthorities());
            throw new UsernameNotFoundException("用户名不存在");
        }
        String Bypassword = sysUserService.SelectPassword(username);
        String encode = passwordEncoder.encode(Bypassword);
        SysUser sysUser=new SysUser();
        sysUser.setPassword(encode);
        SysRole sysRole = sysUserService.SelectRole(userInfo.getId());
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority(sysRole.getRole_name()));
        List<String> authority = sysUserService.selectIdAuthority(sysRole.getId());
        if (authority == null) {
            userInfo.setAuthorities(authorities);
            return new User(userInfo.getUsername(), userInfo.getPassword(), userInfo.getAuthorities());
        } else {
            for (String au : authority) {
                authorities.add(new SimpleGrantedAuthority(au));
            }
            userInfo.setAuthorities(authorities);
            return new User(userInfo.getUsername(), userInfo.getPassword(), userInfo.getAuthorities());
        }
    }
}
